//
//  SearchCarViewController.m
//  cityCar
//
//  Created by yao on 14-11-5.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SearchCarViewController.h"
#import "WebColor.h"
#import "Connection.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#import "SeekBrandDetailCell.h"
#import "SeekWebViewController.h"

@interface SearchCarViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain)UITableView *myTableView;
// 存放数据的数组
@property(nonatomic, retain)NSMutableArray *chiArraySection;
@property(nonatomic, retain)NSMutableArray *chiArrayRow;
@property(nonatomic, retain)NSMutableDictionary *chiDictionary;

@end

@implementation SearchCarViewController

- (void)dealloc
{
    [_car release];
    [_myTableView release];
    [_chiArraySection release];
    [_chiArrayRow release];
    [_chiDictionary release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.chiArraySection = [NSMutableArray array];
        self.chiArrayRow = [NSMutableArray array];
        self.chiDictionary = [NSMutableDictionary dictionary];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupView];
    [self startDetailConnection];
    [self setupRefresh];
}
- (void)setupView
{
    // 屏幕宽度，屏幕高度
    CGFloat x = self.view.frame.size.width;
    CGFloat y = self.view.frame.size.height;

    // 顶部View
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, x, 64)];
    headView.backgroundColor = [WebColor whiteSmoke];
    [self.view addSubview:headView];
    [headView release];
    
    // 顶部View上的button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(10, 30, 25, 25);
    [button setImage:[UIImage imageNamed:@"iconfont-fanhui.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    button.tintColor = [WebColor black];
    [headView addSubview:button];
    
    // 顶部View上的label
    UILabel *headLabel = [[UILabel alloc] initWithFrame:CGRectMake((x - 80) / 2, 20, 80, 50)];
    headLabel.text = self.car.name;
    headLabel.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:headLabel];
    [headLabel release];
    
    // tableView
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, x, y - 64) style:UITableViewStylePlain];
    self.myTableView.backgroundColor = [WebColor white];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.rowHeight = 70;
    [self.view addSubview:self.myTableView];
    [_myTableView release];
}

- (void)startDetailConnection
{
    // 品牌找车中，点击每个品牌弹出的其子类，根据每个品牌的Id拼接其子类的接口
    NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/price/getSerialListByBrandId/%@", self.car.Id];
    [Connection networkHandlerWith:str block:^(id result) {
        
        NSMutableArray *array = [result objectForKey:@"manufacturers"];
        // 初始化区数组
        self.chiArraySection = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            // 把区的名字存到区数组中
            NSString *str = [dic objectForKey:@"name"];
            [self.chiArraySection addObject:str];
            // 遍历子类数组，存到chiArrayRow数组中
            NSMutableArray *arr = [dic objectForKey:@"serials"];
            self.chiArrayRow = [NSMutableArray array];
            for (NSDictionary *dic1 in arr) {
                Car *car = [[Car alloc] init];
                // kvc赋值
                [car setValuesForKeysWithDictionary:dic1];
                // 把Model类存到chiArrayRow数组中
                [self.chiArrayRow addObject:car];
                
            }
            // 把区名当做key值，子类数组当做value值，存入chiDictionary字典中
            [self.chiDictionary setValue:self.chiArrayRow forKey:str];
        }
        // 刷新页面
        [self.myTableView reloadData];
        
    }];
    
    // 2秒后刷新表格
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //刷新表格
        [self.myTableView reloadData];
        //调用endRefreshing可以结束刷新状态
        [self.myTableView footerEndRefreshing];
//        _countx += 1;
    });
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 刷新表格
        [self.myTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView  headerEndRefreshing];
    });
}
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.myTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.myTableView headerBeginRefreshing];
    
}


// 点击返回按钮的方法
- (void)buttonClicked:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - tableview 协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.chiArraySection.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.chiArraySection[section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arr2 = [self.chiDictionary objectForKey:[self.chiArraySection objectAtIndex:section]];
    return arr2.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SeekBrandDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseseek"];
    if (!cell) {
        cell = [[[SeekBrandDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseseek"] autorelease];
    }
    NSMutableArray *arr = [self.chiDictionary objectForKey:[self.chiArraySection objectAtIndex:(indexPath.section)]];
    Car *car = arr[indexPath.row];
    cell.car = car;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SeekWebViewController *seekWeb = [[SeekWebViewController alloc] init];
    Car *car = [[self.chiDictionary objectForKey:[self.chiArraySection objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    NSMutableString *string = [NSMutableString stringWithFormat:@"http://price.pcauto.com.cn/sg%@/", car.Id];
    seekWeb.Idurl = string;
    [self presentViewController:seekWeb animated:YES completion:^{
        
    }];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
